package com.uduemc.biso.node.module.common.controller;

import com.github.pagehelper.PageInfo;
import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.node.core.common.entities.FormInfoData;
import com.uduemc.biso.node.core.dto.FeignFindInfoFormInfoData;
import com.uduemc.biso.node.core.dto.FeignResponseFormInfoTotal;
import com.uduemc.biso.node.core.entities.SFormInfo;
import com.uduemc.biso.node.module.common.service.CFormInfoService;
import com.uduemc.biso.node.module.service.SFormInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 提交表单服务控制器
 *
 * @author guanyi
 */
@RestController
@RequestMapping("/common/forminfo")
public class CFormInfoController {

    private static final Logger logger = LoggerFactory.getLogger(CFormInfoController.class);

    @Autowired
    private CFormInfoService cFormInfoServiceImpl;

    @Autowired
    private SFormInfoService sFormInfoServiceImpl;

    /**
     * 添加前台提交的表单内容至数据库当中！
     *
     * @param formInfoData
     * @param errors
     * @return
     */
    @PostMapping("/insert")
    public RestResult insert(@Valid @RequestBody FormInfoData formInfoData, BindingResult errors) {
        logger.info("insert: " + formInfoData.toString());
        if (errors.hasErrors()) {
            Map<String, Object> message = new HashMap<>();
            for (FieldError fieldError : errors.getFieldErrors()) {
                String field = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();
                message.put(field, defaultMessage);
            }
            return RestResult.error(message);
        }

        SFormInfo data = cFormInfoServiceImpl.insert(formInfoData);
        return RestResult.ok(data, SFormInfo.class.toString());
    }

    /**
     * 通过 hostId以及 formIds 获取每一个 formId对应的数据总数
     *
     * @param hostId
     * @param formIds
     * @return
     */
    @PostMapping("/total-by-hostid-formids")
    public RestResult total(@RequestParam("hostId") long hostId, @RequestParam("formIds") List<Long> formIds) {
        if (CollectionUtils.isEmpty(formIds)) {
            return RestResult.noData();
        }

        List<FeignResponseFormInfoTotal> result = new ArrayList<FeignResponseFormInfoTotal>();
        for (Long formId : formIds) {
            int totla = sFormInfoServiceImpl.totlaByHostFormId(hostId, formId);
            FeignResponseFormInfoTotal feignResponseFormInfoTotal = new FeignResponseFormInfoTotal();
            feignResponseFormInfoTotal.setHostId(hostId).setFormId(formId).setTotal(totla);
            result.add(feignResponseFormInfoTotal);
        }
        return RestResult.ok(result, FeignResponseFormInfoTotal.class.toString(), true);
    }

    /**
     * 通过参数 feignFindInfoFormInfoData 条件过滤数据！
     *
     * @param feignFindInfoFormInfoData
     * @param errors
     * @return
     */
    @PostMapping("/find-infos-by-form-id-search-page")
    public RestResult findInfosByFormIdSearchPage(
            @Valid @RequestBody FeignFindInfoFormInfoData feignFindInfoFormInfoData, BindingResult errors) {
        logger.info("findInfosByFormIdSearchPage: " + feignFindInfoFormInfoData.toString());
        if (errors.hasErrors()) {
            Map<String, Object> message = new HashMap<>();
            for (FieldError fieldError : errors.getFieldErrors()) {
                String field = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();
                message.put(field, defaultMessage);
            }
            return RestResult.error(message);
        }
        PageInfo<FormInfoData> pageInfoFormInfoData = cFormInfoServiceImpl
                .findInfosByFormIdSearchPage(feignFindInfoFormInfoData);
        return RestResult.ok(pageInfoFormInfoData);
    }

    /**
     * 通过 hostId、formId、formInfoId 删除前台提交的所有表单数据！
     *
     * @param hostId
     * @param formId
     * @param formInfoId
     * @return
     */
    @GetMapping("/delete-forn-info-by-host-forminfo-id/{hostId:\\d+}/{formId:\\d+}/{formInfoId:\\d+}")
    public RestResult deleteFornInfoByHostFormInfoId(@PathVariable("hostId") long hostId,
                                                     @PathVariable("formId") long formId, @PathVariable("formInfoId") long formInfoId) {
        SFormInfo sFormInfo = sFormInfoServiceImpl.findOneByHostFormIdAndId(formInfoId, hostId, formId);
        if (sFormInfo == null) {
            return RestResult.error();
        }
        cFormInfoServiceImpl.deleteFornInfoByHostFormInfoId(sFormInfo);
        return RestResult.ok(sFormInfo, SFormInfo.class.toString());
    }
}
